﻿using System.Diagnostics;

namespace IPScanner
{
    public partial class IPRangeMetric : UserControl
    {
        ToolTip toolTip = new ToolTip();

        public Control RectContainer => pl;

        private int _start = 1;
        private int _end = 254;

        public IPRangeMetric()
        {
            InitializeComponent();
        }

        public IPRangeMetric(int start, int end) : this()
        {
            _start = start;
            _end = end;

            InitRect();
        }

        private void InitRect()
        {
            pl.Padding = new Padding(5);
            pl.AutoScroll = true;
            for (int i = _start; i <= _end; i++)
            {
                var lbl = new Label
                {
                    AutoSize = false,
                    Size = new Size(40, 20),
                    Margin = new Padding(0, 0, 5, 5),
                    Text = i.ToString(),
                    TextAlign = ContentAlignment.MiddleCenter,
                    BorderStyle = BorderStyle.FixedSingle,
                    BackColor = Color.White,
                    Name = $"lbl{i}"
                };
                lbl.MouseHover += (s, e) =>
                {
                    var item = lbl.Tag as HostItem;
                    if(item != null) toolTip.Show($"延迟：{item?.ReplayTime ?? 0}ms", lbl);
                };

                pl.Controls.Add(lbl);
            }
        }

        public void InitStatus()
        {
            pl.UpdateUI(() =>
            {
                foreach (Control c in pl.Controls) c.BackColor = Color.White;
            });
        }

        public void UpdateStatus(HostItem hostItem, bool isError)
        {
            var lbl = pl.Controls[$"lbl{hostItem.Address.Substring(hostItem.Address.LastIndexOf('.') + 1)}"];
            if (lbl is null) return;
            if (!isError) lbl.Tag = hostItem;
            lbl.UpdateUI(() =>
            {
                if (isError) lbl.BackColor = Color.FromArgb(224, 224, 224);
                else if (hostItem.ReplayTime > 10) lbl.BackColor = Color.FromArgb(100, 149, 237);
                else lbl.BackColor = Color.FromArgb(146, 228, 146);
                lbl.Invalidate();
            });
        }
    }
}
